/*
 * @lc app=leetcode.cn id=54 lang=typescript
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
function spiralOrder(matrix: number[][]): number[] {
  const DIRECTION = [
    [0, 1],
    [1, 0],
    [0, -1],
    [-1, 0],
  ]
  const [M, N] = [matrix.length, matrix[0].length]
  // 边界值
  let [top, bottom, left, right] = [0, M - 1, 0, N - 1]
  // 坐标索引、方向
  let [i, j, d] = [0, 0, 0]
  const res: number[] = []
  let count = 0
  while (count++ < M * N) {
    res.push(matrix[i][j])
    if (
      i + DIRECTION[d][0] < top ||
      i + DIRECTION[d][0] > bottom ||
      j + DIRECTION[d][1] < left ||
      j + DIRECTION[d][1] > right
    ) {
      switch (d) {
        case 0:
          top++
          break
        case 1:
          right--
          break
        case 2:
          bottom--
          break
        case 3:
          left++
          break
      }
      d = (d + 1) % 4
    }
    i += DIRECTION[d][0]
    j += DIRECTION[d][1]
  }
  return res
}
// @lc code=end
// debugger
// const test0 = [
//   [1, 2, 3],
//   [4, 5, 6],
//   [7, 8, 9],
// ]
// console.log("期待输出：[1, 2, 3, 6, 9, 8, 7, 4, 5]")
// console.log("实际输出：", spiralOrder(test0))
